﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ExamCommon;

namespace ExamServerBLL
{

    /// <summary>
    /// 服务端用户服务
    /// </summary>
    public class UserService
    {
        /// <summary>
        /// 已经登录的用户列表, key 表示学号, value存储conncetedSocketDictionary集合中的key
        /// </summary>
        public static ConcurrentDictionary<string, string> loginSuccessDictionary = new ConcurrentDictionary<string, string>();

        /// <summary>
        /// 存储控制UI相应的委托
        /// </summary>
        public static List<Action<string>> userServiceActions = new List<Action<string>>();

        public static void initAction(List<Action<string>> actions)
        {
            userServiceActions.AddRange(actions);
        }

        /// <summary>
        /// 用户登录服务
        /// </summary>
        /// <param name="msg"></param>
        public static void UserLogin(Message msg)
        {
            LoginDTO info = msg.objectData as LoginDTO;
            Console.WriteLine("info 收到登录请求消息, 学号: " + info.studentNo + " 姓名: " + info.name);
            Message returnMsg = new Message();
            // 校验用户登录, 如果该用户已经登录, 则返回重复登录的提示
            if (loginSuccessDictionary.ContainsKey(info.studentNo))
            {
                // 向客户端返回重复登录的消息
                returnMsg.msgCommand = MsgCommand.REPEAT_LOGIN;
                ServerSocketService.SendMessage(ServerSocketService.conncetedSocketDictionary[ServerSocketService.GenerateKey(msg)], returnMsg);
                return;
            }
            // 将用户信息添加至登录集合中
            if (loginSuccessDictionary.TryAdd(info.studentNo, ServerSocketService.GenerateKey(msg)))
            {
                // 向客户端返回登录成功消息
                returnMsg.msgCommand = MsgCommand.LOGIN_SUCCESS;
                ServerSocketService.SendMessage(ServerSocketService.conncetedSocketDictionary[loginSuccessDictionary[info.studentNo]], returnMsg);
                Console.WriteLine("info 用户: " + info.name + " / " + info.studentNo + " 登录成功!");
                userServiceActions[0]("用户: " + info.name + " 已登录 "); // userServiceActions[0] 气泡提示用户登录成功
            }
        }
    }
}
